import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class JsonViewerFixedLineBreaks extends StatefulWidget {
  final String jsonString;
  final double fontSize;
  final int indentSpaces;

  const JsonViewerFixedLineBreaks({
    Key? key,
    required this.jsonString,
    this.fontSize = 14.0,
    this.indentSpaces = 2,
  }) : super(key: key);

  @override
  _JsonViewerFixedLineBreaksState createState() => _JsonViewerFixedLineBreaksState();
}

class _JsonViewerFixedLineBreaksState extends State<JsonViewerFixedLineBreaks> {
  dynamic _jsonData;
  String? _errorMessage;
  String? _formattedJson; // 存储格式化后的JSON，用于调试

  @override
  void initState() {
    super.initState();
    _parseAndFormatJson();
  }

  @override
  void didUpdateWidget(covariant JsonViewerFixedLineBreaks oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.jsonString != widget.jsonString) {
      _parseAndFormatJson();
    }
  }

  void _parseAndFormatJson() {
    try {
      _jsonData = json.decode(widget.jsonString);
      _errorMessage = null;
      // 生成格式化的JSON并存储用于调试
      _formattedJson = _formatJsonWithLineBreaks(_jsonData, 0);
      // 调试：打印格式化后的JSON，确认包含换行符
      debugPrint("Formatted JSON with line breaks: $_formattedJson");
    } catch (e) {
      _jsonData = null;
      _formattedJson = null;
      if (e is FormatException) {
        _errorMessage = 'JSON格式错误: ${e.message}\n错误位置: ${e.offset}';
      } else {
        _errorMessage = '解析失败: $e';
      }
    }
    setState(() {});
  }

  // 确保换行的格式化方法，每个层级明确添加换行
  String _formatJsonWithLineBreaks(dynamic jsonData, int indentLevel) {
    // 基础缩进计算
    final String indent = " " * (indentLevel * widget.indentSpaces);
    final String nextIndent = " " * ((indentLevel + 1) * widget.indentSpaces);

    // 空值处理
    if (jsonData == null) {
      return "null";
    }

    // 字符串类型
    if (jsonData is String) {
      return "\"${jsonData.replaceAll("\"", "\\\"")}\"";
    }

    // 数字类型
    if (jsonData is num) {
      return jsonData.toString();
    }

    // 布尔类型
    if (jsonData is bool) {
      return jsonData ? "true" : "false";
    }

    // Map类型（JSON对象）
    if (jsonData is Map) {
      // 空对象
      if (jsonData.isEmpty) {
        return "{}";
      }

      // 非空对象：强制换行
      final StringBuffer buffer = StringBuffer();
      buffer.writeln("{"); // 明确使用writeln添加换行

      final List<dynamic> keys = jsonData.keys.toList();
      for (int i = 0; i < keys.length; i++) {
        final dynamic key = keys[i];
        final dynamic value = jsonData[key];
        final bool isLast = i == keys.length - 1;

        // 添加键值对，明确缩进
        buffer.write("$nextIndent\"$key\": ");
        // 递归处理值
        buffer.write(_formatJsonWithLineBreaks(value, indentLevel + 1));
        // 最后一个元素不加逗号
        buffer.write(isLast ? "" : ",");
        buffer.writeln(); // 每个键值对后强制换行
      }

      buffer.write("$indent}");
      return buffer.toString();
    }

    // List类型（JSON数组）
    if (jsonData is List) {
      // 空数组
      if (jsonData.isEmpty) {
        return "[]";
      }

      // 非空数组：强制换行
      final StringBuffer buffer = StringBuffer();
      buffer.writeln("["); // 明确使用writeln添加换行

      for (int i = 0; i < jsonData.length; i++) {
        final bool isLast = i == jsonData.length - 1;

        // 添加元素，明确缩进
        buffer.write(nextIndent);
        // 递归处理元素
        buffer.write(_formatJsonWithLineBreaks(jsonData[i], indentLevel + 1));
        // 最后一个元素不加逗号
        buffer.write(isLast ? "" : ",");
        buffer.writeln(); // 每个元素后强制换行
      }

      buffer.write("$indent]");
      return buffer.toString();
    }

    // 其他类型
    return jsonData.toString();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("JSON查看器"),
      ),
      body: Container(
        color: Colors.black87,
        width: double.infinity,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: _buildContent(),
        ),
      ),
    );
  }

  Widget _buildContent() {
    if (_errorMessage != null) {
      return SingleChildScrollView(
        child: Text(
          _errorMessage!,
          style: const TextStyle(
            color: Colors.redAccent,
            fontFamily: 'monospace',
            fontSize: 14,
          ),
        ),
      );
    }

    if (_formattedJson == null) {
      return const Center(child: Text("无数据"));
    }

    // 使用SelectableText确保换行正常且文本可选中
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: SingleChildScrollView(
        child: SelectableText(
          _formattedJson!,
          style: const TextStyle(
            color: Colors.white,
            fontFamily: 'monospace',
            fontSize: 14,
            height: 1.3, // 增加行高，让换行更清晰
          ),
          // 明确设置文本换行方式
          textDirection: TextDirection.ltr,
          toolbarOptions: const ToolbarOptions(
            copy: true,
            selectAll: true,
          ),
        ),
      ),
    );
  }
}

// 使用示例
class JsonLineBreakExample extends StatelessWidget {
  final String testJson = '''
  {
    "name": "JSON换行测试",
    "version": 1.0,
    "features": [
      "强制换行",
      "明确缩进",
      "可选中文本"
    ],
    "settings": {
      "indent": 2,
      "lineHeight": 1.3,
      "fontFamily": "monospace"
    },
    "dataTypes": {
      "string": "这是字符串",
      "number": 12345,
      "boolean": true,
      "nullValue": null,
      "nestedObject": {
        "key": "value",
        "anotherKey": "anotherValue"
      },
      "nestedArray": [
        1,
        2,
        3,
        [
          "a",
          "b",
          "c"
        ]
      ]
    }
  }
  ''';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: JsonViewerFixedLineBreaks(
        jsonString: testJson,
        fontSize: 14,
        indentSpaces: 2,
      ),
    );
  }
}


